package cn.wenhaha.common.config;



import cn.wenhaha.common.core.domain.AjaxV1Result;
import cn.wenhaha.common.exception.ApiMSGException;
import org.pf4j.DependencyResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {
    Logger log = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(value = ApiMSGException.class)
    public AjaxV1Result errorHandler(ApiMSGException exception) {
        log.error(exception.getMessage());
        return  AjaxV1Result.error(exception);
    }

    @ExceptionHandler(value = BindException.class)
    public AjaxV1Result errorHandler(BindException exception) {
        log.error(exception.getMessage());
        FieldError fe = exception.getFieldError();
        return  AjaxV1Result.newFail(fe.getDefaultMessage());
    }

    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public AjaxV1Result errorHandler(HttpMessageNotReadableException exception) {
        log.error(exception.getMessage());
        return  AjaxV1Result.newFail("响应体为空");
    }
    @ExceptionHandler(value = DependencyResolver.DependenciesNotFoundException.class)
    public AjaxV1Result<?> errorPlugin(DependencyResolver.DependenciesNotFoundException exception) {
        log.error(exception.getMessage());
        List<String> dependencies = exception.getDependencies();
        return  AjaxV1Result.newFail( "该插件需要以下数据源插件支持： "+dependencies.toString() );
    }

    @ExceptionHandler(value = Exception.class)
    public AjaxV1Result exception(Exception e){
        e.printStackTrace();
        if (e.getClass().getName().equals("cn.dev33.satoken.exception.NotRoleException")){
            return  AjaxV1Result.newFail("角色不符合");
        }
        if (e.getClass().getName().equals("cn.dev33.satoken.exception.NotLoginException")){
            return  AjaxV1Result.newFail("用户过期，请重新登录");
        }
        log.error(e.getMessage());
        return  AjaxV1Result.newFail(e.getMessage());
    }


}
